import { createRouter, createWebHashHistory } from "vue-router";
// import { constantRoute, asnycRoute, anyRoute } from "./routes";
import { constantRoute, asnycRoute } from "./routes";
import nprogress from "nprogress";
import "nprogress/nprogress.css";
import pinia from "@/store";
import useUserStore from "@/store/modules/user";
let userStore = useUserStore(pinia);
const router = createRouter({
  history: createWebHashHistory(),
  routes: [...constantRoute], //路由配置
  //滚动行为
  scrollBehavior() {
    return {
      left: 0,
      top: 0,
    };
  },
});
//全局守卫
router.beforeEach(async (to, from, next) => {
  nprogress.start();
  let token = userStore.token;
  //获取用户名字
  let username = userStore.username;
  if (token) {
    //登录成功,访问login,不能访问,指向首页
    if (to.path == "/login") {
      next({ path: "/" });
    } else {
      //登录成功访问其余六个路由(登录排除)
      //有用户信息
      if (username) {
        //放行
        next();
      } else {
        //如果没有用户信息,在守卫这里发请求获取到了用户信息再放行
        try {
          //获取用户信息
          await userStore.userInfo();
          //放行
          // 添加动态路由
          if (!userStore.routesLoaded) {
            asnycRoute.forEach((route) => {
              router.addRoute(route);
            });
            // router.addRoute(anyRoute); // 添加任意路由
            userStore.routesLoaded = true; // 标记动态路由已加载
          }

          // 确保路由目标更新后的放行
          return next({ ...to, replace: true });
          //万一:刷新的时候是异步路由,有可能获取到用户信息、异步路由还没有加载完毕,出现空白的效果
          // next({ ...to });
        } catch (error) {
          //token过期:获取不到用户信息了
          //用户手动修改本地存储token
          //退出登录->用户相关的数据清空
          await userStore.userLogout();
          next({ path: "/login", query: { redirect: to.path } });
        }
      }
    }
  } else {
    if (to.path == "/login") {
      next();
    } else {
      next({ path: "/login", query: { redirect: to.path } });
    }
  }
});
//后置守卫
router.afterEach((to, from) => {
  nprogress.done();
});
export default router;
